package com.gao.listener;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.stereotype.Component;

/**
 * Consumer ACK机制
 *  1.设置手动签收
 *  2.实现ChannelAwareMessageListener接口
 *  3. 如果消息处理成功,调用basicAck手动签收,否则调用basicNack拒绝签收,broker重新发送给consumer
 * @author gaofeng
 * @date 2022年09月07日 21:09
 */
@Component
public class AckListener implements ChannelAwareMessageListener {
    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        long consumerTag = message.getMessageProperties().getDeliveryTag();
        try {
           // 1.接收转换消息
           System.out.println(new String(message.getBody()));
           // 2.处理
            System.out.println("处理业务逻辑...");
           //3.手动签收
           channel.basicAck(consumerTag, true);
       } catch (Exception e) {
            // 第三个参数,代表重回队列,设置为true时,消息重新回到queue,broker会重新发送该消息给消费端
           channel.basicNack(consumerTag, true, true);
           channel.basicReject(consumerTag, true);
       }
    }
}
